package db

import (
	"bgs/conf"
	pgdb "bgs/db/sqlc"
	"database/sql"
	"fmt"
	"go.uber.org/zap"
)

const (
	dbDriver = "postgres"
)

// PgDao pgsql access database
type PgDao struct {
	conn *sql.DB
	Q    *pgdb.Queries
	slog *zap.SugaredLogger
}

// New get a instance of PgDao
func New(dbConf conf.PgSection, slog *zap.SugaredLogger) *PgDao {
	dbSource := fmt.Sprintf(
		"postgresql://%s:%s@%s:%s/%s?sslmode=disable",
		dbConf.User,
		dbConf.Password,
		dbConf.Host,
		dbConf.Port,
		dbConf.Database,
	)
	conn, err := sql.Open(dbDriver, dbSource)
	if err != nil {
		slog.Panicf("connecting db err:%s", err)
	}
	var status string
	row := conn.QueryRow("select 'ok' AS status ")

	err = row.Scan(
		&status,
	)
	if err != nil {
		slog.Panicf("scan db row err:%s", err)
	}

	if status != "ok" {
		slog.Panicf("unable to connect db")
	}

	slog.Infof("db connect status:%s", status)

	return &PgDao{slog: slog, conn: conn, Q: pgdb.New(conn)}
}

// NewTxRunner create a new TxRunner
func (dao *PgDao) NewTxRunner() *pgdb.TxRunner {
	return pgdb.NewTxRunner(dao.conn)
}
